import axios from "axios";

axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = "application/x-www.form-urlencoded;charset=UTF-8"

// 配置拦截器
axios.interceptors.request.use(
    (config)=>{
        return config;
    },
    (error)=>{
        return Promise.error(error)
    }
)

//响应拦截器
axios.interceptors.response.use(
    (config)=>{
        if(response.status === 200){
            return Promise.resolve(response.data)
        }else{
            return Promise.reject(response.data)
        }
    },
    (error)=>{
        console.log(error);
    }
)

// 定义一个ajax请求
export default function ajax(url="", params={}, type='GET'){
    let promise
    return new Promise((resolve,reject)=>{
        if(type.toUpperCase() === 'GET'){
            params["woshiyige"] = randomCode(20)
            promise = axios({
                url,params,
            })
        }else if(type.toUpperCase() === 'POST'){
            promise = axios({
                url,data:params
            })
        }

        promise.then((response)=>{
            resolve(response)
        }).catch((error)=>{
            reject(error)
        })
    })
}


function randomCode(length){
    const chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    let result = ''
    for(let i=0; i<length; i++){
        let index = Math.ceil(Math.random()*9)
        result += chars[index]
    }
    
    return result
}
